<template>
  <el-form :model="editData" label-width="120px" class="edit-pile-form">
    <!-- 图片上传 -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="站点图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/upload/images"
              :file-list="fileList"
              list-type="picture-card"
              :limit="1"
              :auto-upload="true"
              :on-success="handleUploadSuccess"
              :on-remove="handleUploadRemove"
              :on-exceed="handleExceed"
          >
            <i v-if="fileList.length === 0" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 基本信息 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="充电桩名称">
          <el-input v-model="editData.pileName"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="充电桩编号">
          <!-- 新增时可编辑编号，编辑时也可禁用（根据需求） -->
          <el-input
              v-model="editData.pileCode"
              :disabled="!isAdd"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="类型">
          <el-input v-model="editData.pileType"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="功率(kW)">
          <el-input-number v-model="editData.pilePower" :min="0"/>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="状态">
          <el-select v-model="editData.pileStatus">
            <el-option label="空闲中" value="空闲中"/>
            <el-option label="使用中" value="使用中"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="型号">
          <el-input v-model="editData.pileModel"/>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="描述">
          <el-input v-model="editData.pileDesc"/>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 充电枪列表 -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="充电枪列表">
          <el-table :data="editData.chargingGuns" style="width: 100%" border>
            <el-table-column prop="gunName" label="充电枪名称"/>
            <el-table-column prop="gunCode" label="充电枪编号"/>
            <el-table-column prop="gunType" label="类型"/>
            <el-table-column prop="outputPower" label="输出功率(kW)"/>
            <el-table-column prop="remark" label="备注"/>
            <el-table-column label="操作">
              <template #default="{ row, $index }">
                <el-button size="small" @click="openEditGunDialog(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="removeGun($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="openNewGunDialog">新增充电枪</el-button>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 底部按钮 -->
    <div style="text-align: right; margin-top: 15px;">
      <el-button @click="cancelDialog">取消</el-button>
      <el-button type="primary" @click="saveForm">
        {{ isAdd ? "确认新增" : "确认编辑" }}
      </el-button>
    </div>
  </el-form>

  <!-- 新增充电枪 弹窗 -->
  <el-dialog v-model="gunDialogVisible" title="新增充电枪">
    <el-form :model="newGunForm" label-width="120px">
      <el-form-item label="枪名称">
        <el-input v-model="newGunForm.gunName"/>
      </el-form-item>

      <el-form-item label="枪编号">
        <el-input v-model="newGunForm.gunCode"/>
      </el-form-item>

      <el-form-item label="枪类型">
        <el-input v-model="newGunForm.gunType"/>
      </el-form-item>

      <el-form-item label="输出功率(kW)">
        <el-input-number v-model="newGunForm.outputPower"/>
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="newGunForm.remark"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveNewGun">保存</el-button>
        <el-button @click="gunDialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 编辑充电枪 弹窗 -->
  <el-dialog v-model="gunEditDialogVisible" title="编辑充电枪">
    <el-form :model="editGunForm" label-width="120px">
      <el-form-item label="枪名称">
        <el-input v-model="editGunForm.gunName"/>
      </el-form-item>

      <el-form-item label="枪编号">
        <!-- 编辑时可禁用 gunCode -->
        <el-input v-model="editGunForm.gunCode" disabled/>
      </el-form-item>

      <el-form-item label="枪类型">
        <el-input v-model="editGunForm.gunType"/>
      </el-form-item>

      <el-form-item label="输出功率(kW)">
        <el-input-number v-model="editGunForm.outputPower"/>
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="editGunForm.remark"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveEditGun">保存</el-button>
        <el-button @click="gunEditDialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { ref, reactive } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "EditPileForm",
  props: {
    editData: {
      type: Object,
      required: true,
    },
    isAdd: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["refresh", "close"],
  setup(props, { emit }) {
    // 直接使用 props.editData
    const editData = props.editData;

    // 文件列表（图片上传用）
    const fileList = ref(
        editData.pileImgUrl
            ? [{ name: "站点图片", url: editData.pileImgUrl }]
            : []
    );

    // 新增/编辑充电枪弹窗
    const gunDialogVisible = ref(false);
    const gunEditDialogVisible = ref(false);

    // 新增表单
    const newGunForm = reactive({
      gunName: "",
      gunCode: "",
      gunType: "",
      outputPower: 0,
      remark: "",
    });

    // 编辑表单
    const editGunForm = reactive({
      gunName: "",
      gunCode: "",
      gunType: "",
      outputPower: 0,
      remark: "",
    });

    const handleUploadSuccess = (response) => {
      if (response) {
        editData.pileImgUrl = response;
        ElMessage.success("图片上传成功");
      } else {
        ElMessage.error("图片上传失败");
      }
    };
    const handleUploadRemove = () => {
      fileList.value = [];
      editData.pileImgUrl = "";
    };
    const handleExceed = () => {
      ElMessage.error("只能上传一张图片");
    };

    // 打开“新增充电枪”弹窗
    const openNewGunDialog = () => {
      Object.assign(newGunForm, {
        gunName: "",
        gunCode: "",
        gunType: "",
        outputPower: 0,
        remark: "",
      });
      gunDialogVisible.value = true;
    };

    // 打开“编辑充电枪”弹窗
    const openEditGunDialog = (gun) => {
      Object.assign(editGunForm, gun);
      gunEditDialogVisible.value = true;
    };

    // 新增 - 保存
    const saveNewGun = () => {
      const isDuplicate = editData.chargingGuns.some(
          (gun) => gun.gunCode === newGunForm.gunCode
      );
      if (isDuplicate) {
        ElMessage.error("充电枪编号已存在，请更换");
        return;
      }

      editData.chargingGuns.push({ ...newGunForm });
      gunDialogVisible.value = false;
    };

    const saveEditGun = () => {
      // 修正重复校验逻辑，排除当前编辑的枪
      const isDuplicate = editData.chargingGuns.some(
          (gun) =>
              gun.gunCode === editGunForm.gunCode && gun !== editGunForm
      );
      if (isDuplicate) {
        ElMessage.error("充电枪编号已存在，请更换");
        return;
      }

      const index = editData.chargingGuns.findIndex(
          (gun) => gun.gunCode === editGunForm.gunCode
      );
      if (index !== -1) {
        editData.chargingGuns.splice(index, 1, { ...editGunForm });
      }
      gunEditDialogVisible.value = false;
    };

    // 删除枪
    const removeGun = (index) => {
      ElMessageBox.confirm("确定要删除该充电枪吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            editData.chargingGuns.splice(index, 1);
            ElMessage.success("删除成功");
          })
          .catch(() => {
            ElMessage.info("已取消操作");
          });
    };

    // 保存表单（当前充电桩 + 所有充电枪）
    const saveForm = async () => {
      try {
        if (props.isAdd) {
          await axios.post("/chargingPile/createChargingPilesWithChargingGun", {
            pile: { ...editData },
            chargingGuns: editData.chargingGuns,
          });
          ElMessage.success("新增成功");
        } else {
          await axios.post("/chargingPile/updateChargingPilesWithChargingGun", {
            chargingPile: { ...editData },
            chargingGuns: editData.chargingGuns,
          });
          ElMessage.success("更新成功");
        }
        emit("refresh");
        emit("close");
      } catch (error) {
        console.error(props.isAdd ? "新增失败" : "更新失败", error);
        ElMessage.error(props.isAdd ? "新增失败" : "更新失败");
      }
    };

    // 取消
    const cancelDialog = () => {
      emit("close");
    };

    return {
      editData,
      fileList,
      gunDialogVisible,
      gunEditDialogVisible,
      newGunForm,
      editGunForm,

      handleUploadSuccess,
      handleUploadRemove,
      handleExceed,

      openNewGunDialog,
      openEditGunDialog,
      saveNewGun,
      saveEditGun,
      removeGun,
      saveForm,
      cancelDialog,
    };
  },
};
</script>

<style scoped>
.edit-pile-form {
  padding-bottom: 20px;
}
</style>